package com.eurobcoin.filter;

import java.io.IOException;
import java.net.InetAddress;
import java.util.Date;
import java.util.Enumeration;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.eurobcoin.ApplicationConst;
import com.eurobcoin.dao.model.HttpRequestLog;
import com.eurobcoin.main.RequestKeys;
import com.eurobcoin.main.SessionKeys;
import com.eurobcoin.user.User;

public class HttpRequestLogFilter implements Filter {

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		HttpServletRequest httpRequest = (HttpServletRequest)request;
		HttpSession httpSession = httpRequest.getSession();
		
		User user = (User)httpSession.getAttribute(SessionKeys.USER);
		
		String instanceName = InetAddress.getLocalHost().getCanonicalHostName();
		
		String userAddress = httpRequest.getHeader("X-Real-IP");
		
		String uri = httpRequest.getRequestURI(); 
		String parametersString = this.getParametersString(httpRequest);
		
		HttpRequestLog httpRequestLog = new HttpRequestLog();
		httpRequestLog.setLog_start(new Date());
		httpRequestLog.setLog_instance_name(instanceName);
		httpRequestLog.setLog_user_ip(userAddress);
		httpRequestLog.setLog_error(ApplicationConst.NO_VALUE);
		httpRequestLog.setLog_url(uri);
		httpRequestLog.setLog_parameters(parametersString);
		
		if(user != null) {
			httpRequestLog.setLog_user_name(user.getUserName());
			httpRequestLog.setLog_user_rol(user.getUserRol());
		}
		
		httpRequestLog.setLog_session_id(httpSession.getId());
		
		httpRequest.setAttribute(RequestKeys.HTTP_REQUEST_LOG, httpRequestLog);
		
		chain.doFilter(request, response);
		
	}

	private String getParametersString(HttpServletRequest request) {
		StringBuilder sb = new StringBuilder();
		
		Enumeration<String> names = request.getParameterNames();
		while(names.hasMoreElements()) {
			String paramName = names.nextElement();
			String paramValue = request.getParameter(paramName);
			
			if(paramValue.length() > 100) {
				paramValue = paramValue.substring(0, 100);
			}
			
			sb.append(paramName);
			sb.append("=");
			sb.append(paramValue);
			sb.append("&");
		}
		
		String ret = sb.toString();
		if(ret.length() != 0) {
			ret = ret.substring(0, ret.length() - 1);
		}
		
		return ret;
	}

	public void init(FilterConfig filterConfig) throws ServletException {
		
	}
	
	public void destroy() {
		
	}
	
}
